import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./userStore";
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart";
export const useCartStore = defineStore(
  "cart",
  () => {
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);
    //定义state - cartList
    const cartList = ref([]);
    const allPrice = computed(() => {
      return cartList.value.reduce((a, b) => a + b.count * b.price, 0);
    });
    const allCount = computed(() => {
      return cartList.value.reduce((a, b) => a + b.count, 0);
    });

    const updateNewList = async () => {
      const res = await findNewCartListAPI();
      cartList.value = res.result;
    };
    //定义action -addCart
    const addCart = async (goods) => {
      const { skuId, count } = goods;
      if (isLogin.value) {
        //登录之后的加入购物车逻辑
        await insertCartAPI({ skuId, count });
        updateNewList();
      } else {
        const item = cartList.value.find((item) => goods.skuId === item.skuId);
        if (item) item.count++;
        else cartList.value.push(goods);
      }
    };

    //定义action - 删除购物车
    const delCart = async (skuId) => {
      if (isLogin.value) {
        //调用接口
        await delCartAPI([skuId]);
        updateNewList();
      } else {
        // 找下标 splice
        // 或 数组过滤 filter
        // const idx = cartList.value.findIndex((item) => skuId === item.skuId);
        // cartList.value.splice(idx, 1);
        cartList.value = cartList.value.filter((item) => item.skuId !== skuId);
      }
    };

    //action - 清除购物车
    const clearCart = () => {
      cartList.value = [];
    };

    const singleCheck = (skuId, selected) => {
      cartList.value.find((item) => item.skuId === skuId).selected = selected;
    };
    const isAll = computed(() => cartList.value.every((item) => item.selected));
    const allCheck = (selected) => {
      cartList.value.forEach((item) => (item.selected = selected));
    };

    const selectedCount = computed(() =>
      cartList.value.filter((item) => item.selected).reduce((a, b) => a + b.count, 0)
    );
    const selectedPrice = computed(() =>
      cartList.value.filter((item) => item.selected).reduce((a, b) => a + b.count * b.price, 0)
    );
    return {
      isLogin,
      cartList,
      allCount,
      allPrice,
      isAll,
      selectedCount,
      selectedPrice,
      updateNewList,
      addCart,
      delCart,
      singleCheck,
      allCheck,
      clearCart,
    };
  },
  {
    persist: true,
  }
);
